# 1. 创建更大的临时空间（使用/code目录）
export TMPDIR=/code/tmp
mkdir -p $TMPDIR
export PIP_TEMP_DIR=$TMPDIR
export NUITKA_CACHE_DIR=$TMPDIR/nuitka

# 2. 设置pip缓存到/code（避免使用受限的/root目录）
export PIP_CACHE_DIR=/code/.pip-cache
mkdir -p $PIP_CACHE_DIR

# 3. 使用阿里云镜像加速
export PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/
export PIP_TRUSTED_HOST=mirrors.aliyun.com

# 4. 关键优化：分步安装并清理缓存
echo "Step 1: Installing base dependencies..."
pip install --no-cache-dir --no-deps numpy==1.23.5 pandas==1.5.3

echo "Step 2: Cleaning up to free space..."
pip cache purge
rm -rf /root/.cache/pip/*

echo "Step 3: Installing OpenCV (headless version)..."
pip install --no-cache-dir --no-deps opencv-python-headless==4.8.1.78

echo "Step 4: Cleaning up again..."
pip cache purge
rm -rf /root/.cache/pip/*

echo "Step 5: Installing pre-compiled PyTorch (AVOIDING NCCL)..."
# 使用cu117版本，不依赖nvidia_nccl_cu12
pip install --no-cache-dir \
  https://download.pytorch.org/whl/cu117/torch-1.13.1%2Bcu117-cp39-cp39-linux_x86_64.whl \
  https://download.pytorch.org/whl/cu117/torchvision-0.14.1%2Bcu117-cp39-cp39-linux_x86_64.whl

echo "Step 6: Cleaning up before ultralytics..."
pip cache purge
rm -rf /root/.cache/pip/*

echo "Step 7: Installing ultralytics with minimal dependencies..."
pip install --no-cache-dir --no-deps ultralytics==8.2.0

echo "Step 8: Final cleanup..."
pip cache purge
rm -rf /root/.cache/pip/*